package com.qs.javame.thread.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试中断3：测试ReentrantLock.lock()、ReentrantLock.lockInterruptibly()时线程发生中断
 */
public class Testinterrupt4 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Task());
        thread.start();

        //线程中断
        thread.interrupt();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("main线程执行完了~");
    }

    static class Task implements Runnable {

        ReentrantLock reentrantLock = new ReentrantLock();


        @Override
        public void run() {
            try {
                try {
                    /**
                     *  阻塞等待获取锁，同时响应中断，存在两种结果：
                     *  1、在等待获取锁时，如果线程被中断，则抛出InterruptedException，并清除中断标识位，isInterrupted()返回false；
                     *  2、获取锁的时候，未中断线程，获取锁之后，发生中断，则不会抛出InterruptedException，中断标识位不会被清除，
                     *  isInterrupted()返回true；
                     *  3、直接使用reentrantLock.lock()操作，不会响应中断，当线程发生中断时，中断标识位不会被清除，isInterrupted()
                     *  返回true；
                     */

                    reentrantLock.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName() + "-获取锁");
                    int i = 100000;
                    while (i > 0) {
                        i--;
                    }

                    System.out.println("i=" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //返回false
                    System.out.println(Thread.currentThread().getName() + "-中断1：" + Thread.currentThread().isInterrupted());
                }
            } finally {
                System.out.println(Thread.currentThread().getName() + "-释放锁");
                reentrantLock.unlock();
            }

            //返回true
            System.out.println(Thread.currentThread().getName() + "-中断2：" + Thread.currentThread().isInterrupted());
        }
    }
}
